#ifndef FOUNDATION_DISCOVERY_SERVER_IMPL_H
#define FOUNDATION_DISCOVERY_SERVER_IMPL_H

#include "discovery_server.h"
#include "utils_noncopyable.h"
#include "utils_log.h"
#include <uv.h>
#include <string>
#include <thread>
#include <atomic>
#include <functional>
#include <vector>
#include "protocol.h"

namespace El {
namespace Discovery {

class DiscoveryServerImpl : public IDiscoveryServer, public NoCopyable {

public:
    DiscoveryServerImpl();
    ~DiscoveryServerImpl();

    bool Start() override;
    void Stop() override;

private:
    // libuv循环和句柄
    uv_loop_t *loop_ = nullptr;
    uv_udp_t udpHandle_{};
    uv_timer_t broadcastTimer_{};
    std::thread loopThread_;
    std::atomic<bool> running_{false};
    Protocol::IProtocolPtr protocol_;

    // 多播配置
    static const char *MULTICAST_ADDR;
    static const int PORT;
    struct sockaddr_in sendAddr_{};

    // 静态回调函数
    static void OnAllocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf);
    static void OnUdpRecv(uv_udp_t *handle,
                          ssize_t nread,
                          const uv_buf_t *buf,
                          const struct sockaddr *addr,
                          unsigned flags);
    static void OnUdpSend(uv_udp_send_t *req, int status);
    static void WalkCallback(uv_handle_t *handle, void *arg);

    // 成员函数回调
    void HandleUdpRecv(ssize_t nread, const uv_buf_t *buf, const struct sockaddr *addr, unsigned flags);

    // 辅助方法
    void RunLoop();
    void StopLoopHandles();

    // HTTP辅助方法
    bool ParseHttpMessage(const std::string &raw_data, std::string &headers, std::string &body);
    std::string BuildHttpResponse(int statusCode, const std::string &contentType, const std::string &body);
};

} // namespace Discovery
} // namespace El

#endif // FOUNDATION_DISCOVERY_SERVER_IMPL_H
